// 图片上传管理系统
class UploadManager {
    constructor(authManager) {
        this.authManager = authManager;
        this.uploadedPhotos = this.loadUploadedPhotos();
        this.init();
    }

    init() {
        this.bindEvents();
        this.setupDragAndDrop();
    }

    // 加载上传的照片数据
    loadUploadedPhotos() {
        const photos = localStorage.getItem('gallery_photos');
        return photos ? JSON.parse(photos) : [];
    }

    // 保存照片数据
    savePhotos() {
        localStorage.setItem('gallery_photos', JSON.stringify(this.uploadedPhotos));
    }

    // 绑定事件
    bindEvents() {
        // 文件选择
        const fileInput = document.getElementById('file-input');
        if (fileInput) {
            fileInput.addEventListener('change', (e) => {
                this.handleFiles(e.target.files);
            });
        }

        // 上传按钮
        const uploadBtn = document.getElementById('upload-btn');
        if (uploadBtn) {
            uploadBtn.addEventListener('click', () => {
                this.startUpload();
            });
        }

        // 取消上传
        const cancelBtn = document.getElementById('cancel-upload');
        if (cancelBtn) {
            cancelBtn.addEventListener('click', () => {
                this.cancelUpload();
            });
        }
    }

    // 设置拖拽上传
    setupDragAndDrop() {
        const dropZone = document.getElementById('drop-zone');
        if (!dropZone) return;

        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            dropZone.addEventListener(eventName, this.preventDefaults, false);
        });

        ['dragenter', 'dragover'].forEach(eventName => {
            dropZone.addEventListener(eventName, () => {
                dropZone.classList.add('border-yellow-500', 'bg-yellow-500/10');
            }, false);
        });

        ['dragleave', 'drop'].forEach(eventName => {
            dropZone.addEventListener(eventName, () => {
                dropZone.classList.remove('border-yellow-500', 'bg-yellow-500/10');
            }, false);
        });

        dropZone.addEventListener('drop', (e) => {
            const files = e.dataTransfer.files;
            this.handleFiles(files);
        }, false);
    }

    preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }

    // 处理选择的文件
    handleFiles(files) {
        const fileArray = Array.from(files);
        const validFiles = fileArray.filter(file => this.validateFile(file));

        if (validFiles.length === 0) {
            this.authManager.showMessage('请选择有效的图片文件', 'error');
            return;
        }

        this.previewFiles(validFiles);
    }

    // 验证文件
    validateFile(file) {
        // 检查文件类型
        const validTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
        if (!validTypes.includes(file.type)) {
            return false;
        }

        // 检查文件大小（最大10MB）
        const maxSize = 10 * 1024 * 1024;
        if (file.size > maxSize) {
            return false;
        }

        return true;
    }

    // 预览文件
    previewFiles(files) {
        const previewContainer = document.getElementById('preview-container');
        if (!previewContainer) return;

        previewContainer.innerHTML = '';

        files.forEach((file, index) => {
            const reader = new FileReader();
            reader.onload = (e) => {
                const previewItem = this.createPreviewItem(e.target.result, file, index);
                previewContainer.appendChild(previewItem);
            };
            reader.readAsDataURL(file);
        });

        // 显示预览区域
        const previewSection = document.getElementById('preview-section');
        if (previewSection) {
            previewSection.classList.remove('hidden');
        }
    }

    // 创建预览项
    createPreviewItem(dataURL, file, index) {
        const div = document.createElement('div');
        div.className = 'relative bg-gray-800 rounded-lg p-4';
        div.innerHTML = `
            <div class="aspect-square mb-4">
                <img src="${dataURL}" alt="预览" class="w-full h-full object-cover rounded-lg">
            </div>
            <div class="space-y-3">
                <input type="text" placeholder="照片标题" 
                       class="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:border-yellow-500"
                       id="title-${index}">
                <textarea placeholder="照片描述" rows="2"
                          class="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:border-yellow-500 resize-none"
                          id="description-${index}"></textarea>
                <input type="text" placeholder="标签 (用逗号分隔)" 
                       class="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:border-yellow-500"
                       id="tags-${index}">
                <div class="flex items-center justify-between">
                    <label class="flex items-center text-sm text-gray-300">
                        <input type="checkbox" id="private-${index}" class="mr-2">
                        设为私有
                    </label>
                    <button onclick="this.parentElement.parentElement.parentElement.remove()" 
                            class="text-red-400 hover:text-red-300 text-sm">
                        删除
                    </button>
                </div>
            </div>
        `;
        return div;
    }

    // 开始上传
    async startUpload() {
        if (!this.authManager.requireLogin()) return;

        const previewItems = document.querySelectorAll('#preview-container > div');
        if (previewItems.length === 0) {
            this.authManager.showMessage('请先选择要上传的图片', 'warning');
            return;
        }

        const uploadData = [];
        previewItems.forEach((item, index) => {
            const img = item.querySelector('img');
            const title = item.querySelector(`#title-${index}`).value || '未命名';
            const description = item.querySelector(`#description-${index}`).value || '';
            const tags = item.querySelector(`#tags-${index}`).value || '';
            const isPrivate = item.querySelector(`#private-${index}`).checked;

            uploadData.push({
                dataURL: img.src,
                title: title,
                description: description,
                tags: tags.split(',').map(tag => tag.trim()).filter(tag => tag),
                private: isPrivate,
                fileName: `uploaded_${Date.now()}_${index}.jpg`
            });
        });

        await this.uploadPhotos(uploadData);
    }

    // 上传照片
    async uploadPhotos(photos) {
        const progressContainer = document.getElementById('upload-progress');
        if (progressContainer) {
            progressContainer.classList.remove('hidden');
        }

        for (let i = 0; i < photos.length; i++) {
            const photo = photos[i];
            await this.uploadSinglePhoto(photo, i, photos.length);
        }

        // 上传完成
        this.authManager.showMessage(`成功上传 ${photos.length} 张照片！`, 'success');
        
        // 重置上传界面
        setTimeout(() => {
            this.resetUploadInterface();
        }, 2000);
    }

    // 上传单张照片
    uploadSinglePhoto(photo, index, total) {
        return new Promise((resolve) => {
            const progressBar = document.getElementById(`progress-${index}`);
            const progressText = document.getElementById(`progress-text-${index}`);
            
            if (!progressBar) {
                // 创建进度条
                const progressItem = document.createElement('div');
                progressItem.className = 'mb-4';
                progressItem.innerHTML = `
                    <div class="flex justify-between items-center mb-2">
                        <span class="text-sm text-gray-300">${photo.title}</span>
                        <span id="progress-text-${index}" class="text-sm text-gray-400">0%</span>
                    </div>
                    <div class="w-full bg-gray-700 rounded-full h-2">
                        <div id="progress-${index}" class="bg-yellow-500 h-2 rounded-full transition-all duration-300" style="width: 0%"></div>
                    </div>
                `;
                
                const progressContainer = document.getElementById('upload-progress-container');
                if (progressContainer) {
                    progressContainer.appendChild(progressItem);
                }
            }

            // 模拟上传进度
            let progress = 0;
            const interval = setInterval(() => {
                progress += Math.random() * 15;
                if (progress >= 100) {
                    progress = 100;
                    clearInterval(interval);
                    
                    // 保存照片数据
                    this.savePhotoData(photo);
                    resolve();
                }
                
                if (progressBar) {
                    progressBar.style.width = progress + '%';
                }
                if (progressText) {
                    progressText.textContent = Math.round(progress) + '%';
                }
            }, 100);
        });
    }

    // 保存照片数据
    savePhotoData(photo) {
        const currentUser = this.authManager.getCurrentUser();
        if (!currentUser) return;

        const photoData = {
            id: this.generateId(),
            url: photo.dataURL,
            title: photo.title,
            description: photo.description,
            tags: photo.tags,
            category: 'user-upload',
            private: photo.private,
            uploadDate: new Date().toISOString(),
            uploaderId: currentUser.id,
            uploaderName: currentUser.nickname || currentUser.username,
            likes: 0,
            views: 0,
            comments: []
        };

        this.uploadedPhotos.push(photoData);
        this.savePhotos();

        // 更新用户的上传记录
        currentUser.uploadedPhotos.push(photoData.id);
        this.authManager.updateUserInfo(currentUser);
    }

    // 取消上传
    cancelUpload() {
        const previewSection = document.getElementById('preview-section');
        const progressContainer = document.getElementById('upload-progress');
        
        if (previewSection) {
            previewSection.classList.add('hidden');
        }
        if (progressContainer) {
            progressContainer.classList.add('hidden');
        }
        
        // 清空预览
        const previewContainer = document.getElementById('preview-container');
        if (previewContainer) {
            previewContainer.innerHTML = '';
        }
        
        // 清空文件输入
        const fileInput = document.getElementById('file-input');
        if (fileInput) {
            fileInput.value = '';
        }
    }

    // 重置上传界面
    resetUploadInterface() {
        this.cancelUpload();
        
        // 跳转到个人中心
        setTimeout(() => {
            window.location.href = 'profile.html';
        }, 1000);
    }

    // 获取用户上传的照片
    getUserPhotos(userId) {
        return this.uploadedPhotos.filter(photo => photo.uploaderId === userId);
    }

    // 获取公开照片
    getPublicPhotos() {
        return this.uploadedPhotos.filter(photo => !photo.private);
    }

    // 搜索照片
    searchPhotos(query) {
        const allPhotos = this.getPublicPhotos();
        const lowercaseQuery = query.toLowerCase();
        
        return allPhotos.filter(photo => 
            photo.title.toLowerCase().includes(lowercaseQuery) ||
            photo.description.toLowerCase().includes(lowercaseQuery) ||
            photo.tags.some(tag => tag.toLowerCase().includes(lowercaseQuery)) ||
            photo.uploaderName.toLowerCase().includes(lowercaseQuery)
        );
    }

    // 删除照片
    deletePhoto(photoId) {
        const currentUser = this.authManager.getCurrentUser();
        if (!currentUser) return false;

        const photoIndex = this.uploadedPhotos.findIndex(photo => 
            photo.id === photoId && photo.uploaderId === currentUser.id
        );

        if (photoIndex === -1) return false;

        // 删除照片
        this.uploadedPhotos.splice(photoIndex, 1);
        this.savePhotos();

        // 从用户的上传记录中移除
        const uploadedIndex = currentUser.uploadedPhotos.indexOf(photoId);
        if (uploadedIndex > -1) {
            currentUser.uploadedPhotos.splice(uploadedIndex, 1);
            this.authManager.updateUserInfo(currentUser);
        }

        return true;
    }

    // 生成唯一ID
    generateId() {
        return 'photo_' + Date.now().toString(36) + Math.random().toString(36).substr(2);
    }

    // 获取照片统计信息
    getPhotoStats() {
        const currentUser = this.authManager.getCurrentUser();
        if (!currentUser) return null;

        const userPhotos = this.getUserPhotos(currentUser.id);
        const totalViews = userPhotos.reduce((sum, photo) => sum + photo.views, 0);
        const totalLikes = userPhotos.reduce((sum, photo) => sum + photo.likes, 0);

        return {
            totalPhotos: userPhotos.length,
            totalViews: totalViews,
            totalLikes: totalLikes,
            publicPhotos: userPhotos.filter(photo => !photo.private).length,
            privatePhotos: userPhotos.filter(photo => photo.private).length
        };
    }
}

// 创建全局上传管理器实例
let uploadManager;

// 在DOM加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    if (typeof authManager !== 'undefined') {
        uploadManager = new UploadManager(authManager);
    }
});

// 导出供其他模块使用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = UploadManager;
}